﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using InfoStuffStore.Common;
using System.Xml.Serialization;
namespace InfoStuffStore
{
    /// <summary>
    /// Summary description for RssFeed
    /// </summary>
    public class RssFeed : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            context.Response.Write(GetRssXml());
        }

        private string GetRssXml()
        {
            string result = "";
            rss rssfeed = new rss();
            rssfeed.channel = new rssChannel();
            rssfeed.version = 2.0M;
            rssfeed.channel.title = "Infostuffstore Blog Posts";
            rssfeed.channel.managingEditor = "tech@infostuffstore.com";
            rssfeed.channel.webMaster = "tech@infostuffstore.com";
            rssfeed.channel.link = "http://www.infostuffstore.com";
            rssfeed.channel.language = "en-US";
            rssfeed.channel.description = "A RSS news feed containing the latest articles and blogs for the info stuff store.";
            List<rssChannelItem> channelItems = new List<rssChannelItem>();
            using (DBDataContext dataContext = new DBDataContext())
            {
                List<Blog> blogList = dataContext.Blogs.OrderByDescending(obj => (obj.CreatedDate)).ToList();
                foreach (var item in blogList)
                {
                    channelItems.Add(new rssChannelItem()
                    {
                        guid = Guid.NewGuid().ToString(),
                        link = string.Format("http://www.infostuffstore.com/ViewBlog.aspx?blogid={0}", item.BlogID),
                        title = item.Title,
                        description = item.ShortDesc,
                        pubDate = item.CreatedDate.ToLongDateString()
                    });
                }
            }

            rssfeed.channel.item = channelItems.ToArray();
            result = SerializeRss(rssfeed);
            return result.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        }

        private string SerializeRss(rss rssInput)
        {
            XmlSerializer ser = new XmlSerializer(rssInput.GetType());
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter writer = new System.IO.StringWriter(sb);
            ser.Serialize(writer, rssInput);
            return sb.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}